Ext.define('HIT.controller.ExportCenter', {
    extend: 'Ext.app.Controller',
    //导出回写controller.js
    models : ['Search','ExportWriteBackTask'],
    stores : ['ExportWriteBack','ExportWriteBackTask'],
    views  : ['ExportWriteBackGrid','ExportWriteBackPlan','ExportWriteBackTaskGrid'],
    
    onButtonClick: function(button, e, options) {
    	var tabpanelId = 'tab-export-writeback';
        var tab = Ext.getCmp(tabpanelId);
        
        if (tab == undefined) {
            return;
        }
    	if(button.id == 'export-excel'){   //导出EXCEL
    		var TicketType = Ext.getCmp('writeback-invtype').getValue();  //Nor_VAT(增值税普通)   B(交通运输类税)
//    		var TicketStatus = Ext.getCmp('writeback-invstatus_select').getValue();  //发票状态：已开票，已红冲、已回写
    		var RefreshStatus = Ext.getCmp('writeback-invstatus_select').getValue();
    		var TicketStatus = new Array();
    		var TicketConfig = Share.invoiceInitConfig(TicketType).ACK_ERP_TYPE;   //EXCEL、TXT、数据源(ERP)方式回写，后台未写
//    		var TicketConfig = "数据源";
//    		var TicketConfig = TicketType == "Nor_VAT" ? "TXT" : TicketType == "B" ? "EXCEL" : "数据源";
//    		console.log("TicketType: "+TicketType);
//    		console.log("TicketConfig: "+TicketConfig);
    		var selModel = tab.getSelectionModel();
            if (selModel.hasSelection()){
            	TicketStatus = selModel.getSelection()[0].get('doc_status');
            	var num = selModel.getCount();
            	for(var tn=1;tn<num;tn++){
            		if(TicketStatus != selModel.getSelection()[tn].get('doc_status')){
            			Share.ShowMessage("I0011","同种状态发票");
            			return;
            		}
            	}
            	if(TicketStatus == '已开票'){
            		TicketStatus = '1';
            	}else if(TicketStatus == '已红冲'){
            		TicketStatus = '5';
            	}else if(TicketStatus == '已回写'){
            		TicketStatus = '9';
            	}
                var models = selModel.getSelection();
                var ids = [];
                for(var j=0;j<models.length;j++){
                	if(models[j].get('doc_status') != '已开票' && models[j].get('doc_status') != '已回写' && models[j].get('doc_status') != '已红冲'){
                		Share.showMsg('E','I0072','E0071'," "+models[j].get('document_no')+" ");
                		return;
                	}
                	if(models[j].get('document_no').trim().length >= 1){
                		ids.push("'"+models[j].get('document_no')+"'");         	
                	}
                }
//                var Ids = ids.join(",");
//                var doc_type = Ext.getCmp('writeback-invtype').getValue();
                var ticketnum = models.length;
                var Doc = "("+ids+")";
                Share.AjaxRequest({
                    url: ctx + '/WriteBackDownload/SaveSelectedIds',
                    params: {
                        doc: Doc
                    },
                    callback: function(result) {
                        if (TicketConfig == "TXT") { //TXT回写
                            try {
                                tab.getStore().load({
                                    params: {Doc: Doc, TicketStatus: TicketStatus, type: TicketType}//Doc为单据号，后台收到单据号后，先刷新数据库，再刷新Store
                                });
                                window.location.href = ctx + '/WriteBackDownload/' + TicketType + '/' + ticketnum + '/' + TicketStatus + '/download';   //TXT导出
                            } catch (e) {
                                Share.ShowMessage("I0007", "TXT回写");
                                return;
                            } finally {
                                tab.getStore().reload();
                            }
                        }
                        else if (TicketConfig == "EXCEL") {  //EXCEL回写
                            try {
                                tab.getStore().load({
                                    params: {Doc: Doc, TicketStatus: RefreshStatus, type: TicketType}//Doc为单据号，后台收到单据号后，先刷新数据库，再刷新Store
                                });
                                window.location.href = ctx + '/WriteBackExportExcel/' + TicketStatus + '/download';  //EXCEL导出
                            } catch (e) {
                                Share.ShowMessage("I0007", "EXCEL回写");
                                return;
                            } finally {
                                tab.getStore().reload();
                            }
                        }
                        else if (TicketConfig == "CSV") {  //CSV回写
                            try {
                                tab.getStore().load({
                                    params: {Doc: Doc, TicketStatus: RefreshStatus, type: TicketType}//Doc为单据号，后台收到单据号后，先刷新数据库，再刷新Store
                                });
                                window.location.href = ctx + '/WriteBackExportCsv/' + TicketStatus + '/download';  //CSV导出
                            } catch (e) {
                                Share.ShowMessage("I0007", "CSV回写");
                                return;
                            } finally {
                                tab.getStore().reload();
                            }
                        }
                        else if (TicketConfig == "数据源") {  //ERP回写
                            Share.AjaxRequest({
                                url: ctx + "/writebackexporterp",   //ERP导出
                                params: {
                                    ids: Doc,
                                    TicketStatus: TicketStatus
                                },
                                showMsg: false,
                                callback: function (json) {
                                    tab.getStore().reload();
                                },
                                falseFun: function (json) { //失败后想做的个性化操作函数

                                }
                            });
                        }
                        tab.getStore().reload();
                    }
                });
            }
            else{
            	Share.ShowMessage("I0011","需要操作的行");
				return;
            }
            tab.getStore().reload();
    	}else if(button.id == 'export-search' ){
    		Ext.create('Ext.window.Window', {
			    title: Share.T('查询'),
			    id:'export-writeback-excel',
			    height : 250,
			    width : 450,
			    modal :true,
			    items: [
			    {
			    	xtype:'panel',
			    	height:240,
			    	layout : {
						type : 'absolute'
					},
			    	items:[{
			    		xtype:'combobox',
			    		triggerAction : 'query',
			    		id: 'export-writeback-docNoStart',
                        width: 175,
                        x : 20,
                        y : 20,
                        fieldLabel: Share.T('单据号'),
                        emptyText : Share.T('请输入查询条件...'),
                        valueField : 'value',
        				displayField : 'value',
        				hideTrigger : true, //隐藏下拉箭头  
        				typeAhead : false,
        				queryDelay : 700,
                        labelWidth:60,
                        store : 'DocNo',
        				listeners : {
        					beforequery : function(e) {
            					var combo = e.combo;
            					if(!e.forceAll){   
            						var value = e.query;  
            						var arr = value.split(",");
            						var val = arr[arr.length-1];
            						combo.store.filterBy(function(record,id){   
            							var text = record.get(combo.displayField); 
            							return (text.indexOf(val)!=-1);   
            						});
            						combo.expand();   
            						return false;   
            					}
        					}
        				}
			        },{
			    		xtype:'combobox',
			    		triggerAction : 'query',
			    		id: 'export-writeback-docNoEnd',
                        width: 175,
                        x : 215,
                        y : 20,
                        fieldLabel: Share.T('~'),
                        labelSeparator: ' ',
                        labelWidth:20,
                        emptyText : Share.T('请输入查询条件...'),
                        valueField : 'value',
        				displayField : 'value',
        				hideTrigger : true, //隐藏下拉箭头  
        				typeAhead : false,
        				queryDelay : 700,
                        store : 'DocNo',
        				listeners : {
        					beforequery : function(e) {
            					var combo = e.combo;
            					if(!e.forceAll){   
            						var value = e.query;  
            						var arr = value.split(",");
            						var val = arr[arr.length-1];
            						combo.store.filterBy(function(record,id){   
            							var text = record.get(combo.displayField); 
            							return (text.indexOf(val)!=-1);   
            						});
            						combo.expand();   
            						return false;   
            					}
        					}
        				}
			        },{
				        xtype: 'datefield',
	                    x: 20,
	                    y: 60,
	                    width: 175,
	                    editable : false,
	                    fieldLabel: Share.T('日期'),
	                    id:'export-writeback-dateStart',
	                    tabIndex: 4,
	                    labelWidth: 60,
	                    format		 : 'Y-m-d'
			        }, {
                        xtype: 'datefield',
                        x: 215,
                        y: 60,
                        editable : false,
                        labelWidth: 20,
                        width: 175,
                        id:'export-writeback-dateEnd',
                        tabIndex: 5,
                        fieldLabel: '~',
                        labelSeparator: ' ',
                        format:'Y-m-d'
                    },{
			    		xtype:'combobox',
			    		triggerAction : 'query',
			    		id: 'export-writeback-custCodeStart',
                        width: 175,
                        x : 20,
                        y : 100,
                        fieldLabel: Share.T('客户代码'),
                        labelWidth:60,	
                        valueField : 'name',
						displayField : 'code',
						emptyText : Share.T('请输入查询条件...'),
						hideTrigger : true, // 隐藏下拉箭头
						typeAhead : false,
						queryDelay : 20,
						store : new Ext.data.JsonStore({
							proxy: { 
								type: 'ajax', 
								url : ctx + '/getCustInfo',
								params:{
								},
								reader: { 
									type: 'json', 
									totalProperty: '', 
									root: '' 
								} 
							}, 
						fields:['code','name'], 
	      	            autoLoad:true 
				        }),
	      				listeners : {
	    					beforequery : function(e) {
	        					var combo = e.combo;   
	        					if(!e.forceAll){   
	        						var value = e.query;   
	        						combo.store.filterBy(function(record,id){   
	        							var text = record.get(combo.displayField); 
	        							return (text.indexOf(value)!=-1);   
	        						});
	        						combo.expand();   
	        						return false;   
	        					}
	    					}
	    				}
			        },{
			    		xtype:'combobox',
			    		triggerAction : 'query',
			    		id: 'export-writeback-custCodeEnd',
                        width: 175,
                        x : 215,
                        y : 100,
                        fieldLabel: Share.T('~'),
                        labelSeparator: ' ',
                        emptyText : Share.T('请输入查询条件...'),
                        labelWidth:20,
                        valueField : 'name',
						displayField : 'code',
						hideTrigger : true, // 隐藏下拉箭头
						typeAhead : false,
						queryDelay : 20,
						store : new Ext.data.JsonStore({
							proxy: { 
								type: 'ajax', 
								url : ctx + '/getCustInfo',
								params:{
								},
								reader: { 
									type: 'json', 
									totalProperty: '', 
									root: '' 
								} 
							}, 
						fields:['code','name'], 
	      	            autoLoad:true 
				        }),
	      				listeners : {
	    					beforequery : function(e) {
	        					var combo = e.combo;   
	        					if(!e.forceAll){   
	        						var value = e.query;   
	        						combo.store.filterBy(function(record,id){   
	        							var text = record.get(combo.displayField); 
	        							return (text.indexOf(value)!=-1);   
	        						});
	        						combo.expand();   
	        						return false;   
	        					}
	    					}
	      				}
			        },{
			    		xtype:'combobox',
			    		id: 'export-writeback-invType', //发票类型
                        width: 175,
                        x : 20,
                        y : 140,
                        fieldLabel: Share.T('发票类型'),
                        labelWidth:60,
                        maxLength:50,//对输入框做长度限制
                        valueField : 'value',
						displayField : 'text',
						editable : false,
						value : 'N_VAT',
						store : new Ext.data.JsonStore({
							proxy: {
								type: 'ajax', 
								url : ctx + '/getInvoiceType',
								params:{        	                	
								},
								reader: { 
									type: 'json', 
									totalProperty: '', 
									root: '' 
								}
							}, 
							fields:['text','value'], 
							autoLoad:true
			          })
			        }, {
			    		xtype:'combobox',
			    		id: 'search-invstatus_select', //发票类型
                        width: 175,
                        x : 215,
                        y : 140,
                        fieldLabel: Share.T('发票状态'),
                        labelWidth:60,
                        maxLength:50,//对输入框做长度限制
                        valueField : 'value',
						displayField : 'text',
						editable : false,
						value : '1',
						store: new Ext.data.JsonStore({  
	    					proxy: { 
	        	                type: 'ajax', 
	        	                url : ctx + '/getComboData',
	        	                params:{
	        	                },
	        	                reader: { 
	        	                    type: 'json', 
	        	                    totalProperty: '', 
	        	                    root: '' 
	        	                } 
	        	             }, 
	        	            fields:['text','value'], 
	        	            autoLoad:true 
				        }),
				        listeners : {
				        	beforerender:function(){
				        		this.store.removeAll();
				        		this.store.on('beforeload', function(store) {
				        			Ext.apply(store.proxy.extraParams , {
				        				type : 'exportcenter'
				        			});
				        		});
				        		this.store.load();
				        	}
				        }
			        }]
			    }],
			    buttons : [{
				    	id : 'export-writeback-yes',
				    	width : 70,
				    	text : Share.T('确定')
				    },{
				    	id : 'export-writeback-cancel',
				    	width : 70,
				    	text : Share.T('取消')
			    }]
			}).show();
    	}
    	else if(button.id == 'export-writeback-yes'){
    		var docStart = Ext.getCmp('export-writeback-docNoStart').getValue();
    		var docEnd = Ext.getCmp('export-writeback-docNoEnd').getValue();
    		var dateStart = Ext.getCmp('export-writeback-dateStart').getValue();
    		var dateEnd = Ext.getCmp('export-writeback-dateEnd').getValue();
    		var custCodeStart = Ext.getCmp('export-writeback-custCodeStart').getRawValue();
    		var custCodeEnd = Ext.getCmp('export-writeback-custCodeEnd').getRawValue();
    		var invType = Ext.getCmp('export-writeback-invType').getValue();   	
    		var invStatus = Ext.getCmp('search-invstatus_select').getValue();
    		// 页面隐藏条件与赋值
    		Ext.getCmp('writeback-invtype').setValue(invType);
    		Ext.getCmp('writeback-invstatus_select').setValue(invStatus);
    		
    		var tabPanel = Ext.getCmp('tab-export-writeback');
      		var store = tabPanel.getStore();
      		store.currentPage = 1;
      		store.removeAll();
              store.on('beforeload', function(store) {
         			Ext.apply(store.proxy.extraParams , {docStart:docStart,
                    	docEnd:docEnd,
                    	dateStart:dateStart,
                    	dateEnd:dateEnd,
                    	custCodeStart:custCodeStart,
                    	custCodeEnd:custCodeEnd,
                    	invStatus : invStatus,
                    	invType:invType});
              });
              store.load();             
              Ext.getCmp('export-writeback-excel').close();
    	}else if(button.id == 'export-writeback-cancel'){
    		Ext.getCmp('export-writeback-excel').close();
    	}
    	else if(button.id == 'export-plan'){
    		var p = Share.createPanelByAlias('widget.exportwritebackplan');
        	Share.AjaxRequest({
                url: ctx + "/getwritebackplaninfo",   //获得当前公司设定的计划任务信息
                params: {

                },
                showMsg: false,
                callback: function (json) {
                	if(json==1){
                		Share.ShowMessage("I0007","数据异常，");
                	}else if(json==2){
                		Share.ShowMessage("I0027");
                	}else if(json==3){
                		Share.showPanelAsWindow(p);
                	}else if(json!=null){
                		var START_TIME = json.START_TIME;
                		var END_TIME = json.END_TIME;
                		var LOOP_TYPE = json.LOOP_TYPE;
                		Ext.getCmp('export-startDay').setValue(START_TIME.substr(0, 10));
                        Ext.getCmp('export-startTime').setValue(START_TIME.substr(11, 5));
                        Ext.getCmp('export-endDay').setValue(END_TIME.substr(0, 10));
                        Ext.getCmp('export-endTime').setValue(END_TIME.substr(11, 5));
                		
                		var groupObj = Ext.ComponentMgr.get("export-setGroup");
                		groupObj.items.each(function(item) {
                            if (item.inputValue == LOOP_TYPE) {
                                item.setValue(true);
                            }
                        });
                		Share.showPanelAsWindow(p);
                	}
                },
                falseFun: function (json) { //失败后想做的个性化操作函数
                	
                }
            });
        	
    	}else if(button.id == 'export-view'){
    		var p = Ext.create('widget.exportwritebacktaskgrid');
    		p.show();
    	}
//    	else if(button.id == 'export-txt'){   //导出TXT
//    		var selModel = tab.getSelectionModel();
//            if (selModel.hasSelection()){
//                var models = selModel.getSelection();
//                var ids = [];
//                for(var j=0;j<models.length;j++){
//                	ids.push(models[j].get('id_head_id'));         	
//                }
//                var Ids = ids.join(",");
//                
//            }else{
//            	Ext.Msg.alert(Share.T('错误'), Share.T("没有任何行被选中，无法进行操作！"));
//				return;
//            }        	 
//    	}else if (button.id == 'export-erp'){   //回写ERP
//    		var selModel = tab.getSelectionModel();
//            if (selModel.hasSelection()){
//                var models = selModel.getSelection();
//                var ids = [];
//                for(var j=0;j<models.length;j++){
//                	ids.push(models[j].get('id_head_id'));         	
//                }
//                var Ids = ids.join(",");
//                
//                
//            }else{
//            	Ext.Msg.alert(Share.T('错误'), Share.T("没有任何行被选中，无法进行操作！"));
//				return;
//            }
//    		return;
//    	}
    },
    save: function (win) {
    	var form = Ext.getCmp('panel-exportwritebackplan');
        var basicForm = form.getForm();
        if (!basicForm.isValid()) {
            return;
        }
    	var startDay = Ext.ComponentMgr.get("export-startDay").getValue();
		var startTime = Ext.ComponentMgr.get("export-startTime").getValue();
		var endDay = Ext.ComponentMgr.get("export-endDay").getValue();
		var endTime = Ext.ComponentMgr.get("export-endTime").getValue();
		var export_setGroup = Ext.ComponentMgr.get("export-setGroup").getValue();
		if(startDay==null ||startTime==null || endDay==null || endTime==null){
			Share.ShowMessage("E0051");
			return;
		}
    	Share.AjaxRequest({
            url: ctx + "/savewritebackplaninfo",   //保存当前用户回写计划信息
            params: {
            	startDay  :  startDay,
            	startTime :  startTime,
            	endDay    :  endDay,
            	endTime   :  endTime,
            	LOOP_TYPE :  export_setGroup
            },
            showMsg: false,
            callback: function (json) {
            	if(json==1){
            		Share.ShowMessage("I0007","数据异常，");
            		win.close();
            	}else if(json==2){
            		Share.ShowMessage("I0027");
            	}else if(json==3){
            		Share.ShowMessage("I0006","设置");
                	win.close();
            	}
            	
            },
            falseFun: function (json) { //失败后想做的个性化操作函数
            	
            }
        });
    },
    init: function(application) {
        this.control({
            "button": {
                click: this.onButtonClick
            }
        });
    }
});